package com.example.hrandroidapp;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.components.ObservableScrollView;
import com.example.hrandroidapp.domain.LeavePO;
import com.example.hrandroidapp.domain.UpdatedLeavePO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.google.gson.Gson;

public class LeaveMailDetailActivity extends ActionBarActivity implements ObservableScrollView.Callbacks {
	
	private LeavePO leavePO;
	
	private TextView tvLeaveDays, tvName, tvReason;
    private View mPlaceholderView;
    private ObservableScrollView mObservableScrollView;
    private String isPending;
    private String url;

	private final int OPT_APPROVE = 1;
	private final int OPT_REJECT = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.leave_mail_detail);
		
		Intent intent = getIntent();
		leavePO = (LeavePO) intent.getSerializableExtra("leave");
		isPending = (String) intent.getSerializableExtra("pending");
		
		loadViews(); 
		
        mObservableScrollView.setCallbacks(this);
        
        String startDateTime = (leavePO.getStartDateTime() == null)? "19700101" : leavePO.getStartDateTime();
        String endDateTime = (leavePO.getEndDateTime() == null)? "19700101" : leavePO.getEndDateTime();
        
        tvLeaveDays.setText("From " + DateUtils.getMMMddFormat(startDateTime) + " to " + 
        			DateUtils.getMMMddFormat(endDateTime));
        mPlaceholderView = findViewById(R.id.placeholder);

        mObservableScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        onScrollChanged(mObservableScrollView.getScrollY());
                    }
                });
        
        tvName.setText(leavePO.getEmployeeName());
        tvName.setTypeface(null, Typeface.BOLD);		
        
        tvReason.setText(leavePO.getReason());
	}

	private void loadViews() {
		mObservableScrollView = (ObservableScrollView) findViewById(R.id.scroll_view);
        tvLeaveDays = (TextView) findViewById(R.id.tv_no_of_days);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvReason = (TextView) findViewById(R.id.tv_reason);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(isPending.equals("1"))
			getMenuInflater().inflate(R.menu.pending_leave_detail_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		List<UpdatedLeavePO> lstUpdatedLeaves = new ArrayList<UpdatedLeavePO>();
		UpdatedLeavePO tmpUpdateLeavePO = new UpdatedLeavePO(leavePO.getReason(), leavePO.getLeaveId());
		lstUpdatedLeaves.add(tmpUpdateLeavePO);
		
		switch(item.getItemId()) {
		case R.id.action_approve:
			approveRejectLeavesAPI(lstUpdatedLeaves, true);
		case R.id.action_reject:
			approveRejectLeavesAPI(lstUpdatedLeaves, false);
			
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onScrollChanged(int scrollY) {
		tvLeaveDays.setTranslationY(Math.max(mPlaceholderView.getTop(), scrollY));		
	}

	@Override
	public void onDownMotionEvent() {}

	@Override
	public void onUpOrCancelMotionEvent() {}

	private void approveRejectLeavesAPI(List<UpdatedLeavePO> lstUpdatedLeaves, boolean status) {
		url = getResources().getString(R.string.leave_approve_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(this).getSvrIP() + ":" + Constant.PORT + url;
		
		String updateLeaveArr = new Gson().toJson(lstUpdatedLeaves);
		
		HRLog.postLogInfo("leave approve/reject complete( " + status + "): " + completeUrl, "LeavePendingFragment.loadLeaves");
		new HTTPUtils(this, JSONHTTPPoster.MEDIA_JSON_TYPE, completeUrl, 
				populateRequestParameterMap(status, updateLeaveArr), new HTTPUtils.SimpleRequestResponseTaskInterface() {
					
					@Override
					public void handleResponse(String response, int status) throws Exception {
						if(status == 200) {
							Toast.makeText(LeaveMailDetailActivity.this, "Leave process successful...", Toast.LENGTH_LONG);
							finish();
						}else {
							Toast.makeText(LeaveMailDetailActivity.this, "Fail to process leave process!!!", Toast.LENGTH_LONG);
						}
					}
				}).execute();
	}

	private String populateRequestParameterMap(boolean approve, String updatedLeaveLst) {
		JSONObject approvedData = new JSONObject();
		try {
			approvedData.put("approved", approve);
			approvedData.put("dataList", new JSONArray(updatedLeaveLst)); 
			approvedData.put("loginId", UserPreference.getLoginId(this));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return approvedData.toString();
	}

}
